package bookManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public User findUserByName(String name) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where name = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, name);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                boolean isAdmin = (resultSet.getInt("isAdmin") == 1);
                User user = null;
                if (isAdmin) {
                    user = new Admin();
                } else {
                    user = new NormalUser();
                }
                user.setUserId(resultSet.getInt("userId"));
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
            return null;


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }

//    public static void main(String[] args) {
//        UserDao userDao = new UserDao();
//        User user = userDao.findUserByName("lisi");
//        System.out.println(user);
//    }
}
